package com.github.common.util.system;

import com.github.common.util.lang.StringUtil;

public class EnvUtil {

    public static final String KEY_ENV = "env";

    public static final String DEFAULT_ENV = "local";

    public static final String KEY_ENV_SPRING = "spring.profiles.active";
    public static final String KEY_CLUSTER = "cluster";
    public static final String DEFAULT_CLUSTER = "";

    public static final String SPLITTER = "_";

    public static String getEnvWithCluster() {
        String env = getEnv();
        String cluster = getCluster();
        return DEFAULT_CLUSTER.equals(cluster) ? env : env + SPLITTER + cluster;
    }

    public static String getEnvWithClusterPostfix() {
        return SPLITTER + getEnvWithCluster();
    }

    public static String getEnv() {
        String env = getEnv(KEY_ENV, "");
        if (StringUtil.isEmpty(env)) {
            return getEnv(KEY_ENV_SPRING, DEFAULT_ENV);
        } else {
            return env;
        }
    }

    public static String getCluster() {
        return getEnv(KEY_CLUSTER, DEFAULT_CLUSTER);
    }

    public static String getEnv(String key, String defaultValue) {
        String env = System.getProperty(key);
        if (StringUtil.isNotEmpty(env)) {
            return env;
        }
        env = System.getenv(key);
        if (StringUtil.isNotEmpty(env)) {
            return env;
        }
        return defaultValue;
    }
}
